package com.study.secret;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created on 2021/1/28.
 *
 * 信息摘要
 * SHA1 比 MD5 的 安全性更强
 * 被应用在检查 文件完整性 以及 数字签名 等场景
 * @since 1.0
 */
public class Sha1 {

    public static String computeSHA1(String string) {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA1");
            byte[] data = sha1.digest(string.getBytes());
            return convertBytesToHexString(data);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String content = "Codec<String> simpleTypeCodec = ProtobufProxy.create(String.class);";
        System.out.println(computeSHA1(content));
    }

    /**
     * 功能： 十六进制字符串转字节数组
     * @param hexString 十六进制字符串
     * @return 字节数组
     */
    public static byte[] convertHexStringToBytes(String hexString){
        //判空
        if(hexString == null || hexString.length() == 0) {
            return null;
        }

        //合法性校验
        if(!hexString.matches("[a-fA-F0-9]*") || hexString.length() % 2 != 0) {
            return null;
        }

        //计算
        int mid = hexString.length() / 2;
        byte[]bytes = new byte[mid];
        for (int i = 0; i < mid; i++) {
            bytes[i] = Integer.valueOf(hexString.substring(i * 2, i * 2 + 2), 16).byteValue();
        }

        return bytes;
    }

    /**
     * 字节数组转16进制数
     * @param bytes 字节数组
     * @return 返回值
     */
    public static String convertBytesToHexString(byte[]bytes) {
        StringBuilder res = new StringBuilder("");
        for (byte aByte : bytes) {
            String temp = Integer.toHexString(aByte & 0xff);
            if (temp.length() == 1) {
                temp = '0' + temp;
            }
            res.append(temp);
        }
        return res.toString().toUpperCase();
    }
}
